
import 'package:erp/Entity/Customer.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/Store/AccountStore.dart';
import 'package:erp/Store/CustomerStore.dart';
import 'package:erp/global.dart';

void registerCustomerEvents(){
  globalBus.subscribe(Events.CUSTOMER_SELECT_REQUEST, (bus, _) async {
    try {
      var data = await externalInterface.getAllCustomers(AccountStore.signInResult.token);
      CustomerStore.customers = data;

      bus.publish(Events.CUSTOMER_SELECT_SUCCESS, data);
    }
    catch (exception){
      bus.publish(Events.CUSTOMER_SELECT_ERROR, exception);
    }
  });

  globalBus.subscribe<Customer>(Events.CUSTOMER_INSERT_REQUEST, (bus, data) async {
    try {
      var result = await externalInterface.addCustomer(AccountStore.signInResult.token, data);
      CustomerStore.customers.add(result);

      bus.publish(Events.CUSTOMER_INSERT_SUCCESS, result);
    }
    catch (exception) {
      bus.publish(Events.CUSTOMER_INSERT_ERROR, exception);
    }
  });

  globalBus.subscribe<Customer>(Events.CUSTOMER_UPDATE_REQUEST, (bus, data) async {
    try {
      var result = await externalInterface.updateCustomer(AccountStore.signInResult.token, Customer.fromJson(data.toJson()));
      CustomerStore.customers.singleWhere((item) => item.id == result.id)
      ..type = result.type
      ..memo = result.memo
      ..phone = result.phone
      ..name = result.name
      ..shop = result.shop
      ..updatedAt = result.updatedAt
      ..createdAt = result.createdAt
      ..isremove = result.isremove;

      bus.publish(Events.CUSTOMER_UPDATE_SUCCESS, result);
    }
    catch (exception) {
      bus.publish(Events.CUSTOMER_UPDATE_ERROR, exception);
    }
  });

  globalBus.subscribe<Customer>(Events.CUSTOMER_DELETE_REQUEST, (bus, data) async {
    try {
      var result = await externalInterface.deleteCustomer(AccountStore.signInResult.token, data);
      CustomerStore.customers.removeWhere((item) => item.id == result.id);

      bus.publish(Events.CUSTOMER_DELETE_SUCCESS, result);
    }
    catch (exception) {
      bus.publish(Events.CUSTOMER_DELETE_ERROR, exception);
    }
  });
}
